package com.lingyuan.product.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingyuan.common.core.domain.R;
import com.lingyuan.product.domain.SkuEntity;
import com.lingyuan.product.domain.UserExcel;
import com.lingyuan.product.mapper.UserMapper;
import com.lingyuan.product.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description 描述 导入导出100万用户信息
 * @Author guoxin
 * @Date 2024/9/24 11:21
 */
@RestController
@RequestMapping("/user")
@Log4j2
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 下载模版
     * @param response
     */
    @RequestMapping("/exprottemplate")
    public void downloadTemplate(HttpServletResponse response){
        try {
        //设置文件名
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/用户信息模板.xlsx");
        //设置头文件,注意文件名若为中文，使用encode进行处理
        response.setHeader("Content-disposition", "attachment;fileName=" +  java.net.URLEncoder.encode("用户信息模板.xlsx", "UTF-8"));
        //设置文件传输类型与编码
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导入数据
     * @param file
     * @return
     */
    @PostMapping("/import")
    public Map<String,String> easyExcelImport(@RequestParam MultipartFile file) {
        HashMap<String, String> map = new HashMap<>();
        if (file==null  || file.isEmpty()){
            map.put("msg","文件为空");
            return map;
        }
        try {
            InputStream  inputStream = file.getInputStream();
            userService.importData(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        map.put("msg","文件导入成功");
        return map;
//        if (file.isEmpty()){
//            return R.fail("文件不可为空");
//        }
//        long l = System.currentTimeMillis();
//       // EasyExcel.read(file.getInputStream(), UserExcel.class, new EasyExcelImportHandler()).sheet().doRead();
//        EasyExcel.read(file.getInputStream(),UserExcel.class, new PageReadListener<UserExcel>(userExcels -> {
//            userMapper.insertSelective(userExcels);
//        })).sheet().doRead();;
//        long l1 = System.currentTimeMillis();
//        Long elapsedTime = (l1-l) /1000;
//        System.out.println("耗时："+elapsedTime+"s");
//        return R.ok("文件导入成功");
    }
    /**
     * 导出数据
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            //设置内容类型
            response.setContentType("text/csv");
            //设置响应编码
            response.setCharacterEncoding("utf-8");
            //设置文件名的编码格式,防止文件名乱码
            String fileName = null;
            fileName = URLEncoder.encode("用户信息", "UTF-8");
        //固定写法,设置响应头
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        Integer total = userMapper.countNum();
        if (total == 0) {
            log.info("查询无数据");
            return;
        }
        //指定用哪个class进行写出
        ExcelWriter build = EasyExcel.write(response.getOutputStream(), UserExcel.class).build();
        //设置一个sheet页存储所有导出数据
        WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
        long pageSize = 10000;
        long pages = total / pageSize;
        long startTime = System.currentTimeMillis();
        //数据量只有一页时直接写出
        if(pages < 1){
            List<UserExcel> users = userMapper.selectList(null);
            build.write(users, writeSheet);
        }
        //大数据量时，进行分页查询写入
        for (int i = 0; i <= pages; i++) {
            Page<UserExcel> page = new Page<>();
            page.setCurrent(i + 1);
            page.setSize(pageSize);
            Page<UserExcel> userPage = userMapper.selectPage(page, null);
            build.write(userPage.getRecords(), writeSheet);
        }
        build.finish();
        log.info("导出耗时/ms:"+(System.currentTimeMillis()-startTime)+",导出数据总条数："+total);
        } catch (Exception e) {
            log.error("easyExcel导出失败，e:{}",e.getMessage(),e);
        }
    }
}
